package com.ziyunying.weather.ui.screen

import android.Manifest
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager

import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.ziyunying.weather.repository.LocationRepository
import com.ziyunying.weather.repository.WeatherRepository
import com.ziyunying.weather.ui.screen.model.ForecastItem
import com.ziyunying.weather.ui.screen.util.WeatherDataConverter
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class WeatherViewModel @Inject constructor(
    private val weatherRepository: WeatherRepository,
    private val locationRepository: LocationRepository,
    application: Application
) : AndroidViewModel(application) {

    val weatherDataNow = weatherRepository.weatherDataNow
    val weatherData7d = weatherRepository.weatherData7d
    
    // 添加转换后的天气预报数据
    private val _forecastItems = MutableStateFlow<List<ForecastItem>>(emptyList())
    val forecastItems = _forecastItems.asStateFlow()

    // 默认位置
    private val _currentLocation = MutableStateFlow(locationRepository.getDefaultLocation())

    val currentCity = locationRepository.currentCity

    // 位置权限状态
    private val _locationPermissionGranted = MutableStateFlow(false)
    val locationPermissionGranted = _locationPermissionGranted.asStateFlow()

    // 是否需要显示权限请求对话框
    private val _showPermissionDialog = MutableStateFlow(false)
    val showPermissionDialog = _showPermissionDialog.asStateFlow()

    init {
        checkLocationPermission()
        
        // 观察weatherData7d的变化，并转换数据
        weatherData7d.observeForever { response ->
            _forecastItems.value = WeatherDataConverter.convertToForecastItems(response)
        }
    }

    // 检查位置权限
    fun checkLocationPermission() {
        val hasFineLocationPermission = ContextCompat.checkSelfPermission(
            getApplication(),
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED

        val hasCoarseLocationPermission = ContextCompat.checkSelfPermission(
            getApplication(),
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED

        // 所有必要的权限都已授予
        val allPermissionsGranted = hasFineLocationPermission && hasCoarseLocationPermission

        _locationPermissionGranted.value = allPermissionsGranted
        if (allPermissionsGranted) {
            // 如果有权限，获取位置
            getUserLocation()
        } else {
            // 如果没有权限，显示权限请求对话框
            _showPermissionDialog.value = true
        }
    }

    // 用户授予权限后调用
    fun onPermissionGranted() {
        _locationPermissionGranted.value = true
        _showPermissionDialog.value = false
        getUserLocation()
    }

    // 用户拒绝权限后调用
    fun onPermissionDenied() {
        _locationPermissionGranted.value = false
        _showPermissionDialog.value = false
    }

    // 获取用户位置
    private fun getUserLocation() {
        if (_locationPermissionGranted.value) {
            // 检查位置服务是否开启
            val locationManager =
                getApplication<Application>().getSystemService(Context.LOCATION_SERVICE) as LocationManager
            val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            val isNetworkEnabled =
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)

            if (!isGpsEnabled && !isNetworkEnabled) {
                // 位置服务未开启，不获取数据
                return
            } else {
                // 使用LocationRepository获取位置
                locationRepository.getUserLocation { location ->
                    updateLocation(location)
                }

                // 设置超时处理
                viewModelScope.launch {
                    kotlinx.coroutines.delay(12000) // 12秒超时
                    if (_currentLocation.value == locationRepository.getDefaultLocation()) {
                        // 如果位置还是默认位置，说明定位可能超时，使用默认位置
                        fetchWeatherNow()
                    }
                }
            }
        }
    }

    // 更新位置并获取天气
    fun updateLocation(newLocation: String) {
        _currentLocation.value = newLocation
        fetchWeatherNow(newLocation)
        fetchWeather7d(newLocation)
    }

    // 使用当前位置获取天气
    fun fetchWeatherNow(location: String = _currentLocation.value) {
        viewModelScope.launch {
            weatherRepository.fetchWeatherNow(location)
        }
    }

    fun fetchWeather7d(location: String = _currentLocation.value) {
        viewModelScope.launch {
            weatherRepository.fetchWeather7d(location)
        }
    }
}